import { pinia, useSettingStore } from '@/store'
import { getPermCodeApi } from '@/api/sys/user'
import { getRouteListApi } from '@/api/sys/route'
import { isUrl, transformObjToRoute } from '@/utils'
import { frontRoutes } from '@/router/routes'
import { useUserStore } from './user'

export const useAuthStore = defineStore('auth', () => {
	// 权限标识
	const permCode = ref<string[] | number[]>([])
	// 上次更新Route
	const lastBuildRouteTime = ref<number>(0)
	// 权限路由List
	const routeList = ref<RouterType.RouteItem[]>([])
	// 赋值权限标识
	const setPermCode = (codeList: string[]) => {
		permCode.value = codeList
	}
	// 赋值权限路由List
	const setRouteList = (list: RouterType.RouteItem[]) => {
		routeList.value = jointRoutePath(list, '/')
		list?.length > 0 && setLastBuildRouteTime()
	}
	// 记录更新时间
	const setLastBuildRouteTime = () => {
		lastBuildRouteTime.value = new Date().getTime()
	}
	// 重置状态
	const resetAuth = (): void => {
		routeList.value = []
		permCode.value = []
		lastBuildRouteTime.value = 0
	}
	// 调用接口获取用户权限标识
	const getPermCode = async () => {
		const codeList = await getPermCodeApi()
		setPermCode(codeList)
	}
	// 生成路由
	const buildRoutesAction = async function (): Promise<RouterType.RouteItem[]> {
		let routes: RouterType.RouteItem[] = []
		const { app } = useSettingStore().appSetting
		//后端路由
		if (app.authRoute === 'dynamic') {
			let routeList: RouterType.RouteItem[] = []
			getPermCode()
			routeList = (await getRouteListApi()) as RouterType.RouteItem[]
			routes[0].children = transformObjToRoute(routeList)
		}
		//前端路由
		if (app.authRoute === 'static') {
			routes = frontRoutes
			const { userRoles } = useUserStore()
			routes = filterRoutesByRoles(routes, userRoles)
		}
		setRouteList(routes)
		return routes
	}

	//判断角色是否具有权限
	const hasPermission = (roles: string[], route: RouterType.RouteItem) => {
		const routeRoles = route.meta?.roles
		return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true
	}
	//对路由进行角色权限筛选
	const filterRoutesByRoles = (routes: RouterType.RouteItem[], roles: string[]) => {
		const res: RouterType.RouteItem[] = []
		routes.forEach((route) => {
			const tempRoute = { ...route }
			if (hasPermission(roles, tempRoute)) {
				if (tempRoute.children) {
					tempRoute.children = filterRoutesByRoles(tempRoute.children, roles)
				}
				res.push(tempRoute)
			}
		})
		return res
	}
	// 子路由拼接父级path
	const jointRoutePath = (list: RouterType.RouteItem[], prefix: string): RouterType.RouteItem[] => {
		return list.map((item: RouterType.RouteItem) => {
			if (!isUrl(item.path) && !item.path.startsWith('/')) item.path = prefix + item.path
			if (item.children) item.children = jointRoutePath(item.children, item.path + '/')
			return item
		})
	}
	return {
		permCode,
		lastBuildRouteTime,
		routeList,
		setRouteList,
		resetAuth,
		getPermCode,
		buildRoutesAction,
		hasPermission,
		filterRoutesByRoles
	}
})
// 在组合式setup之外使用
export function useAuthStoreWithout() {
	return useAuthStore(pinia)
}
